﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using MediaMonitor.Common;

namespace MediaMonitor.Admin
{
    public partial class User_Mgmt_List : Adex.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hdnCompanyID.Value = Utility.GetRequestedVal("cid", "0");
            }
        }

        protected void radGrid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {

            DataTable dt;

            if (hdnCompanyID.Value == "0")

                dt = VSiteUser.Query().SetSelectList("*, CONVERT(VARCHAR, DateAdded, 101) AS LastModifiedDate, CONVERT(VARCHAR, ValidTo, 101) AS ValidToDate, CONVERT(VARCHAR, ValidFrom, 101) AS ValidFromDate").WHERE("RoleName", "user").OR("RoleName","advanced user").ORDER_BY("UserName").ExecuteDataSet().Tables[0];

            else
                dt = VSiteUser.Query().SetSelectList("*, CONVERT(VARCHAR, DateAdded, 101) AS LastModifiedDate, CONVERT(VARCHAR, ValidTo, 101) AS ValidToDate, CONVERT(VARCHAR, ValidFrom, 101) AS ValidFromDate").WHERE("RoleName", "user").AND("CompanyCode", hdnCompanyID.Value).ORDER_BY("UserName").ExecuteDataSet().Tables[0];

            radGrid.DataSource = dt;

        }

        protected void radGrid_DeleteCommand(Object source, Telerik.Web.UI.GridCommandEventArgs e)
        {

            string pkId = radGrid.MasterTableView.DataKeyValues[e.Item.ItemIndex]["SiteUserID"].ToString();

            try
            {
                SiteUser usr = new SiteUser(pkId);
                AppUser.DeleteSiteUser(usr);
                SiteUser.Delete(pkId);

            }
            catch
            {
                AjaxFuncs.MsgBox(this, "Failed to delete this record, because related data (child records) exists in other tables");
            }

            radGrid.Rebind();
        }
    }
}